package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
	"time"
)

func init() {
	go func() {
		if tomlInfo.Post == "" {
			// 设置路由和处理函数
			http.HandleFunc("/pay/", payHandler)

			// 启动服务器，监听 2086 端口
			printt("服务器启动，监听 2086 端口...")
			err := http.ListenAndServe(":2086", nil)
			if err != nil {
				log.Fatal("ListenAndServe: ", err)
			}
		}
	}()

}

// 请求处理器函数
func payHandler(w http.ResponseWriter, r *http.Request) {
	// ResponseData 用于定义响应数据的结构
	type writeData struct {
		OrderID int64 `json:"order_id"`
		UserID  int64 `json:"user_id"`
		Price   int64 `json:"price"`
		Paid    int64 `json:"paid"`
		Time    int64 `json:"time"`
	}
	response := writeData{-1, -1, 0, 0, 300}
	type readData struct {
		Key     string `json:"key"`
		OrderID int64  `json:"order_id"`
		UserID  int64  `json:"user_id"`
		Price   int64  `json:"price"`
		Method  int64  `json:"method"`
	}
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Error reading request body", http.StatusBadRequest)
		return
	}
	var payload readData
	if err := json.Unmarshal(body, &payload); err != nil {
		http.Error(w, "Error parsing JSON", http.StatusBadRequest)
		return
	}
	if r.URL.Path == "/pay/get" && payload.Key == tomlInfo.Key {
		orderID, realPrice := addOrder(payload.UserID, payload.Price)
		response = writeData{orderID, payload.UserID, realPrice, 0, 300}
	} else if r.URL.Path == "/pay/check" && payload.Key == tomlInfo.Key {
		order := checkOrder(payload.OrderID)
		response = writeData{order.OrderID, order.UserID, order.Price, order.PayMethod, 300 - time.Now().Unix() + order.CreateTime}
	} else if r.URL.Path == "/pay/post" && payload.Key == tomlInfo.Key {
		orderID := payPrice(payload.Price, payload.Method)
		response = writeData{orderID, -1, payload.Price, payload.Method, 300}
	}
	// 设置响应头为 JSON
	w.Header().Set("Content-Type", "application/json")

	// 序列化响应数据并写入响应体
	json.NewEncoder(w).Encode(response)
}

// 将查询参数 map 转换为字符串
func paramsToString(params map[string][]string) string {
	var paramsList []string
	for key, values := range params {
		for _, value := range values {
			paramsList = append(paramsList, fmt.Sprintf("%s=%s", key, value))
		}
	}
	return strings.Join(paramsList, "&")
}
